﻿<template>
	<el-dialog :title="!dataForm.id ? '新建接口信息' : '编辑接口信息'" :close-on-click-modal="false" :close-on-press-escape="false"
		:visible.sync="visible" lock-scroll width="80%" :append-to-body="true" class="SHZY-dialog SHZY-dialog_center">
		<el-row :gutter="15" class="">
			<el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :rules="rules">
				<el-col :span="24">
					<el-form-item label="接口地址" prop="url">
						<el-input v-model="dataForm.url" placeholder="请输入" clearable required :style='{ "width": "100%" }'>
							<el-select v-model="dataForm.requestMethod" style="width: 90px;" slot="prepend">
								<el-option label="GET" value="GET"></el-option>
								<el-option label="POST" value="POST"></el-option>
							</el-select>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="租户" prop="tenantId">
						<el-select v-model='dataForm.tenantId' placeholder='请选择' clearable required
							:style='{ "width": "100%" }' @change="tenantChange">
							<el-option v-for="(item, index) in tenantIdOptions" :key="index" :label="item.fullName"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="外部系统" prop="tenantExternalId">
						<el-select v-model='dataForm.tenantExternalId' placeholder='请选择' clearable
							:style='{ "width": "100%" }'>
							<el-option v-for="(item, index) in tenantExternalIdOptions" :key="index" :label="item.fullName"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="函数" prop="functionId">
						<el-select v-model='dataForm.functionId' placeholder='请选择' clearable required
							:style='{ "width": "100%" }'>
							<el-option v-for="(item, index) in functionIdOptions" :key="index" :label="item.describe"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="身份信息" prop="authenticationId">
						<el-select v-model='dataForm.authenticationId' placeholder='请选择' clearable
							:style='{ "width": "100%" }'>
							<el-option v-for="(item, index) in authenticationIdOptions" :key="index"
								:label="item.enCode + ' ' + item.fullName" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="Headers" prop="requestHeaders">
						<el-button @click="addHeaders()" class="el-icon-plus" size="mini">添加参数
						</el-button>
						<el-row v-for="(item, index) in requestHeaders" :key="item.index" class="mt-10">
							<el-col :span="10">
								<el-autocomplete v-model="item.field" :fetch-suggestions="querySearch" placeholder="key"
									clearable style="width:100%" />
							</el-col>
							<el-col :span="10" :offset="1">
								<el-input v-model="item.defaultValue" placeholder="value" clearable />
							</el-col>
							<el-col :span="2" :offset="1">
								<el-button type="danger" icon="el-icon-close" @click="removeHeaders(index)">
								</el-button>
							</el-col>
						</el-row>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="自定义参数" prop="requestParameters">
						<el-button @click="addParameters()" class="el-icon-plus" size="mini">添加参数
						</el-button>
						<el-row v-for="(item, index) in requestParameters" :key="item.index" class="mt-10">
							<el-col :span="10">
								<el-autocomplete v-model="item.field" :fetch-suggestions="querySearch" placeholder="key"
									clearable style="width:100%" />
							</el-col>
							<el-col :span="10" :offset="1">
								<el-input v-model="item.defaultValue" placeholder="value" clearable />
							</el-col>
							<el-col :span="2" :offset="1">
								<el-button type="danger" icon="el-icon-close" @click="removeParameters(index)">
								</el-button>
							</el-col>
						</el-row>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="请求数据类型" prop="dataType">
						<el-radio-group v-model='dataForm.dataType' size='small'>
							<el-radio-button v-for="(item, index) in optionsData" :key="index" :label="item.id">{{
								item.fullName }}</el-radio-button>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="请求参数" prop="requestDataProcessing">
						<el-button @click="editFunc(1)">数据处理</el-button>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="返回结果" prop="resultDataProcessing">
						<el-button @click="editFunc(2)">数据处理</el-button>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="备注" prop="remark">
						<el-input v-model='dataForm.remark' placeholder='请输入' show-word-limit :style='{ "width": "100%" }'
							type='textarea' :autosize='{ "minRows": 4, "maxRows": 4 }' maxlength='500'>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="有效标志" prop="enabledMark">
						<el-switch v-model='dataForm.enabledMark' :active-value='1' :inactive-value='0'>
						</el-switch>
					</el-form-item>
				</el-col>
			</el-form>
			<form-script :visible.sync="formScriptVisible" :value="this.dataProcessing" @updateScript="updateScript" />
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确 定</el-button>
		</span>
	</el-dialog>
</template>
  
<script>
import { getInterfaceDetailInfo, createInterfaceDetail, updateInterfaceDetail } from '@/api/system/interface/interface'
import { getTenantAll, getTenantExternalAll } from '@/api/system/interface/tenant'
import { getFunctionAll } from '@/api/system/interface/function'
import { getAuthenticationAll } from '@/api/system/interface/authentication'
import FormScript from './FormScript'
const defaultDataHandler = '(data) => {\r\n    // 处理数据逻辑\r\n\r\n    // 返回所需的数据\r\n    return data\r\n}'

export default {
	components: { FormScript },
	props: [],
	data() {
		return {
			btnLoading: false,
			loading: false,
			visible: false,
			formScriptVisible: false,
			dataType: 0,
			dataProcessing: "",
			dataForm: {
				id: '',
				interfaceId: '',
				tenantId: undefined,
				tenantExternalId: undefined,
				functionId: undefined,
				url: undefined,
				requestMethod: 'GET',
				authenticationId: undefined,
				requestHeaders: '',
				requestParameters: '',
				requestDataProcessing: '',
				resultDataProcessing: '',
				dataType:'Json',
				remark: undefined,
				enabledMark: 1,
			},
			restaurants: [
				{ "value": "Postman-Token" },
				{ "value": "Host" },
				{ "value": "User-Agent" },
				{ "value": "Accept" },
				{ "value": "Accept-Encoding" },
				{ "value": "Connection" }
			],
			requestHeaders: [],
			requestParameters: [],
			rules: {
				interfaceId: [
					{
						required: true,
						message: '请输入接口信息ID',
						trigger: '"change"'
					},
				],
				tenantId: [
					{
						required: true,
						message: '请输入租户ID',
						trigger: '"change"'
					},
				],
				functionId: [
					{
						required: true,
						message: '请输入函数ID',
						trigger: '"change"'
					},
				],
				url: [
					{
						required: true,
						message: '请输入接口地址',
						trigger: '"blur"'
					},
				],
			},
			tenantIdOptions: [],
			tenantExternalIdOptions: [],
			functionIdOptions: [],
			authenticationIdOptions: [],
			optionsData: [{ 'fullName': "Json", 'id': "Json" }, { 'fullName': "JsonArray", 'id': "JsonArray" }],
		}
	},
	computed: {},
	watch: {},
	created() {
		this.getTenantAll()
		this.getTenantExternalAll()
		this.getFunctionAll()
		this.getAuthenticationAll()
	},
	mounted() {
	},
	methods: {
		goBack() {
			this.$emit('refresh')
		},
		getTenantAll() {
			getTenantAll().then(res => {
				this.tenantIdOptions = res.data.list;
			})
		},
		tenantChange() {
			this.dataForm.tenantExternalId = ""
			this.getTenantExternalAll()
		},
		getTenantExternalAll() {
			this.tenantExternalIdOptions = []
			getTenantExternalAll(this.dataForm.tenantId).then(res => {
				this.tenantExternalIdOptions = res.data.list;
			})
		},
		getFunctionAll() {
			getFunctionAll().then(res => {
				this.functionIdOptions = res.data.list;
			})
		},
		getAuthenticationAll() {
			getAuthenticationAll().then(res => {
				this.authenticationIdOptions = res.data.list;
			})
		},
		init(id, interfaceId) {
			this.dataForm.id = id || 0;
			this.dataForm.interfaceId = interfaceId || 0;
			this.requestHeaders = []
			this.requestParameters = []
			this.visible = true;
			this.$nextTick(() => {
				this.$refs['elForm'].resetFields();
				if (this.dataForm.id) {
					getInterfaceDetailInfo(this.dataForm.id).then(res => {
						this.dataForm = res.data;
						if (res.data.requestHeaders) this.requestHeaders = JSON.parse(res.data.requestHeaders) || []
						if (res.data.requestParameters) this.requestParameters = JSON.parse(res.data.requestParameters) || []
						this.getTenantExternalAll()
					})
				}
			});
		},
		querySearch(queryString, cb) {
			const restaurants = this.restaurants;
			const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
			// 调用 callback 返回建议列表的数据
			cb(results);
		},
		createFilter(queryString) {
			return (restaurant) => {
				return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
			};
		},
		removeHeaders(index) {
			this.requestHeaders.splice(index, 1)
		},
		addHeaders() {
			this.requestHeaders.push({
				field: '',
				defaultValue: ''
			})
		},
		removeParameters(index) {
			this.requestParameters.splice(index, 1)
		},
		addParameters() {
			this.requestParameters.push({
				field: '',
				defaultValue: ''
			})
		},
		editFunc(type) {
			this.dataType = type
			if (type == 1) {
				this.dataProcessing = this.dataForm.requestDataProcessing
			} else {
				this.dataProcessing = this.dataForm.resultDataProcessing
			}
			if (!this.dataProcessing) this.dataProcessing = defaultDataHandler
			this.$nextTick(() => {
				this.formScriptVisible = true
			})
		},
		updateScript(data) {
			if (this.dataType == 1) {
				this.dataForm.requestDataProcessing = data
			} else {
				this.dataForm.resultDataProcessing = data
			}
		},
		dataFormSubmit() {
			this.$refs['elForm'].validate((valid) => {
				if (valid) {
					this.btnLoading = true;
					const formMethod = !this.dataForm.id ? createInterfaceDetail : updateInterfaceDetail;
					this.dataForm.requestHeaders = JSON.stringify(this.requestHeaders)
					this.dataForm.requestParameters = JSON.stringify(this.requestParameters)
					formMethod(this.dataForm).then((res) => {
						this.btnLoading = false;
						this.$message({
							message: res.msg,
							type: 'success',
							duration: 1000,
							onClose: () => {
								this.visible = false,
									this.$emit('refreshDataList', true)
							}
						})
					}).catch((res) => {
						this.btnLoading = false;
					})
				}
			})
		},
	}
}
</script>
  